package org.xurui.sxl.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.xurui.sxl.protocol.cache.ConcurrentMapCache;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.LonLat;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 岗位设置/学校设置 A、圆形范围
 */
@Slf4j
public class CmdCodec_POSTSELF implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.POSTSELF.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return true;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //设备回复格式：*XX,YYYYYYYYYYYYYYY,V4,POSTSELF,seq,para,HHMMSS,S,latitude,D,longitude,G,speed,pdop,DDMMYY,tracker_status#
        //设备回复示例：*TJ,2020916301,V4,POSTSELF,130305,1,2212.8745,11346.6574,500,130306,V,2230.7021,N,11355.1445,E,0.0,2.8,271112,FFFFFFFF#
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        String[] payloadArr = payload.replaceAll("\\*","").split(",");
        String deviceId = payloadArr[1];
        report.setDeviceId(deviceId);
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(deviceId+"_"+CommandEnum.POSTSELF.name()+"_"+payloadArr[4]);
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = deviceId+"_"+payloadArr[4];
        }

        report.setFunctionId(CommandEnum.POSTSELF.name());
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        String para=payloadArr[5]+","+payloadArr[6]+","+payloadArr[7]+","+payloadArr[8];

        Map<String, Object> properties = new HashMap<>();
        properties.put("para",para);
        properties.put("uptime",payloadArr[9]);
        properties.put("s",payloadArr[10]);
        properties.put("latitude",BinaryUtils.getWgs84LonLat(payloadArr[11],"lat"));
        properties.put("d",payloadArr[12]);
        properties.put("longitude",BinaryUtils.getWgs84LonLat(payloadArr[13],"lon"));
        properties.put("g",payloadArr[14]);
        properties.put("speed", NumberUtils.parseDouble(payloadArr[15]));
        properties.put("pdop",NumberUtils.parseDouble(payloadArr[16]));
        properties.put("upday", payloadArr[17]);
        String trackerStatusHex = payloadArr[18];


        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        report.setOutput(properties);

        //TODO 更新状态
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //格式：*XX,YYYYYYYYYYYYYYY,POSTSELF,HHMMSS,POSTID,POST_LAT,POST_LON,RADIUS#
        //例子：*TJ,2020916301,POSTSELF,130305,1,2212.8745,11346.6574,500#
        //参数说明：POSTID 岗位/学校组 ID，1-3，最多 3 组
        //参数说明：POST_LAT 岗位/学校纬度；wgs84，格式：DDFF.FFFF，度度分分.分分分分
        //参数说明：POST_LON 岗位/学校经度，wgs84，格式：DDFF.FFFF，度度度分分.分分分分
        //参数说明：RADIUS 半径，整数；单位米；>=0&&<=9999，如设置 0 则该围栏将被删除
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String postId="";
            if(paramsMap.get("postId")!=null && !paramsMap.get("postId").equals("")) {
                postId=paramsMap.get("postId").toString();
            }
            String postLat="";
            if(paramsMap.get("postLat")!=null && !paramsMap.get("postLat").equals("")) {
                postLat=paramsMap.get("postLat").toString();
            }
            String postLon="";
            if(paramsMap.get("postLon")!=null && !paramsMap.get("postLon").equals("")) {
                postLon=paramsMap.get("postLon").toString();
            }
            String radius="";
            if(paramsMap.get("radius")!=null && !paramsMap.get("radius").equals("")) {
                radius=paramsMap.get("radius").toString();
            }

            if(!"".equals(postLat) &&!"".equals(postLon)){
                LonLat lonLat=new LonLat();
                lonLat.lng=Double.parseDouble(postLon);
                lonLat.lat=Double.parseDouble(postLat);

                LonLat aa=BinaryUtils.gcj02towgs84(lonLat);
                postLon=BinaryUtils.getLonLatToWgs84(String.valueOf(aa.lng),"lon");
                postLat=BinaryUtils.getLonLatToWgs84(String.valueOf(aa.lat),"lat");
            }

            String time = SxlMessageUtils.getTimeHHMMSS();

            ConcurrentMapCache.getInstance().set(message.getDeviceId()+"_"+CommandEnum.POSTSELF.name()+"_"+time,message.getMessageId(),60*3*1000);


            return SxlMessageUtils.SxlCmd.getInstance()
                .appendAndAddSeparator(zzs)
                .appendAndAddSeparator(message.getDeviceId())
                .appendAndAddSeparator(CommandEnum.POSTSELF.name())
                .appendAndAddSeparator(time)
                .appendAndAddSeparator(postId)
                .appendAndAddSeparator(postLat)
                .appendAndAddSeparator(postLon)
                .append(radius).buildEncodeMessage();

        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.WIFISCAN.name(),message);
            }
            return null;
        }

    }
}
